package com.cuitrip.business.user.presenter;

import android.text.TextUtils;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.location.model.AreaMode;
import com.cuitrip.business.location.model.LocationMode;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.util.PinYinUtil;
import com.lab.mvp.presenter.Presenter;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by sheena on 16/3/4.
 */
public class CityChoosePresenter implements Presenter<ICityView>, IProxyCallback {
    private ApiProxy mApiProxy = new ApiProxy(this);
    private ICityView mCityView;

    Stack<LocationPoint> stack;
    String[] zxsAbbrs = new String[]{"CN-11", "CN-12", "CN-50", "CN-31"};

    public class LocationPoint {
        public ArrayList<String> index;
        public String title;
        public String abbr;
        public LocationMode locationMode;
        public AreaMode areaMode;
        public HashMap<String, Integer> indexMap;
    }

    public CityChoosePresenter() {
        stack = new Stack<>();
    }

    @Override
    public void attachView(ICityView view) {
        mCityView = view;
    }

    @Override
    public void detachView() {
        mCityView = null;
    }

    public boolean isZXS(String abbr) {
        for (String zxsAbbr : zxsAbbrs) {
            if (abbr.startsWith(zxsAbbr)) {
                return true;
            }
        }
        return false;
    }

    public void loadLocationMode(AreaMode areaMode, String listType) {
        mCityView.displayLoading();
        LocationPoint state = new LocationPoint();
        state.title = areaMode.getName();
        state.areaMode = areaMode;
        state.abbr = areaMode.getAbbr();
        stack.push(state);
        ServiceBusiness.getCountryCity(mApiProxy, state.abbr, listType);
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (mCityView == null) {
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_COUNTRY_CITY.equals(response.getApiName())) {
            handleLocationListResponse(response);
        } else if (ApiManager.MODIFY_USERINFO.equals(response.getApiName())) {
            handleModifyUserInfoResponse(response);
        }
        return false;
    }

    private void handleLocationListResponse(final CtApiResponse response) {
        if (response.isResponseNormal() && response.result instanceof LocationMode) {
            final LocationMode locationMode = (LocationMode) response.result;
            final HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
            //todo onerror没执行，修改
            Observable.just(locationMode).map(new Func1<LocationMode, ArrayList>() {
                @Override
                public ArrayList call(LocationMode locationMode) {
                    List<AreaMode> areaModes = locationMode.getContent();
                    if (areaModes != null) {
                        for (int i = 0; i < areaModes.size(); ++i) {
                            AreaMode areaMode = areaModes.get(i);
                            String firstChar = PinYinUtil.toPinyin(areaMode.getName());
                            areaMode.setFirstChar(firstChar);
                        }
                        Collections.sort(areaModes);
                    }
                    ArrayList<String> indexList = getIndexList(locationMode, indexMap);
                    return indexList;
                }
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<ArrayList>() {
                        @Override
                        public void call(ArrayList list) {
                            if (!stack.isEmpty()) {
                                LocationPoint peek = stack.peek();
                                peek.index = list;
                                peek.locationMode = locationMode;
                                peek.indexMap = indexMap;
                                mCityView.renderUi(locationMode, list, indexMap);
                                mCityView.displayContent();
                            }
                        }
                    });
        } else {
            stack.pop();
            if (TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
            mCityView.displayNoNetwork();
        }
    }

    private void handleModifyUserInfoResponse(final CtApiResponse response) {
        mCityView.hideLoadingDialog();
        if (response.isResponseNormal() && response.result instanceof CtUserInfo) {
            CtUserInfo userInfo = (CtUserInfo) response.result;
            LoginInstance.updateProfile(AppCoreRuntime.context, userInfo, false);
            mCityView.success();
        } else {
            if (TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
        }

    }


    private ArrayList<String> getIndexList(LocationMode
                                                   locationMode, HashMap<String, Integer> indexMap) {
        ArrayList<String> indexList = new ArrayList<>();
        indexList.clear();
        for (int i = 0; i < locationMode.getContent().size(); ++i) {
            String section = String.valueOf(PinYinUtil.toPinyin(locationMode.getContent().get(i).getName()).charAt(0));
            if (!indexMap.containsKey(section)) {
                indexMap.put(section, i);
                indexList.add(section);
            }
        }
        Collections.sort(indexList);
        return indexList;
    }

    public Stack<LocationPoint> getStack() {
        return stack;
    }

    public void saveCity(String countryAbbr, String cityAbbr, String city) {
        mCityView.displayLoadingDialog();
        Map<String, String> params = new HashMap<>();
        params.put("city", city);
        params.put("country", countryAbbr);
        params.put("cityAbbr", cityAbbr);
        UserBusiness.updateProfile(mApiProxy, params);

    }

}
